<template>
  <div class="chart-box">
    <div :id="id" class="chart"></div>
  </div>
</template>

<script setup lang="ts">
import * as echarts from "echarts";
import { onMounted } from "vue";

const porps = defineProps({
  chartData: { type: Object, default: () => {} },
  id: { type: String, default: "chart" },
  color: { type: String, default: "rgba(68, 160, 246, 0.85)" },
});

let chartOption = ref({
  title: {
    // text: "World Population",
  },
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "shadow",
    },
  },
  legend: {},
  grid: {
    top: "0%",
    left: "3%",
    right: "16%",
    bottom: "8%",
    containLabel: true,
  },
  xAxis: {
    show: false,
    axisLine: {
      show: false,
    },
    axisTick: {
      show: false,
    },
    splitLine: {
      show: false,
    },
    type: "value",
    boundaryGap: [0, 0.01],
  },
  yAxis: {
    axisLine: {
      show: false,
    },
    axisTick: {
      show: false,
    },
    splitLine: {
      show: false,
    },
    type: "category",
    data: [
      "Brazil",
      "Indonesia",
      "USA",
      "India",
      "China",
      "World",
      "China",
      "World",
      "China",
      "World",
      "China",
      "World",
    ],
    axisLabel: {
      width: 100,
      overflow: "truncate",
    },
  },
  series: [
    {
      name: "",
      type: "bar",
      data: [
        18203, 23489, 29034, 104970, 131744, 630230, 131744, 630230, 131744,
        630230, 131744, 630230, 131744, 630230,
      ],
      barWidth: "30",
      labelLine: {
        show: false,
      },
      label: {
        show: true,
        position: "right",
      },
      itemStyle: {
        color: porps.color,
      },
    },
  ],
});

watch(
  () => porps.chartData,
  (nVal) => {
    console.log(555, nVal);
    let nValClone = JSON.parse(JSON.stringify(nVal));
    if (nValClone.yData.length < 10) {
      // 数据少于10个的时候手动填充到10个，防止数据对不齐
      let len = nValClone.yData.length;
      nValClone.yData.length = 10;
      nValClone.data.length = 10;
      chartOption.value.yAxis.data = nValClone.yData.fill("", len, 10);
      chartOption.value.series[0].data = nValClone.data.fill("", len, 10);
    } else {
      chartOption.value.yAxis.data = nValClone.yData;
      chartOption.value.series[0].data = nValClone.data;
    }
    chartOption.value.yAxis.data.reverse();
    chartOption.value.series[0].data.reverse();

    nextTick(() => {
      init();
    });
  },
  {
    immediate: true,
    deep: true,
  }
);

onMounted(() => {
  // init();
});

const init = () => {
  // chartOption.value.series;
  var chartDom = document.getElementById(porps.id);
  var myChart = echarts.init(chartDom);

  myChart.setOption(chartOption.value);

  window.onresize = function () {
    myChart.resize();
  };
};
</script>

<style scoped lang="scss">
.chart-box {
  width: 100%;
  height: 100%;
}

.chart {
  width: 100%;
  height: 100%;
}
</style>
